<template>
    <div>
        <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" label-width="120px" class="demo-ruleForm"
            :size="formSize" status-icon>
            <el-form-item label="服务名称" prop="name">
                <el-input v-model="ruleForm.name" placeholder="请输入" />
            </el-form-item>
            <el-form-item label="服务内容" prop="description">
                <el-input v-model="ruleForm.description" placeholder="请输入" type="textarea"/>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="submitForm(ruleFormRef)">
                    确认
                </el-button>
                <el-button @click="resetForm(ruleFormRef)">取消</el-button>
            </el-form-item>
        </el-form>
    </div>
</template>

<script setup>
import { goodsAndServicesUpdate,goodsAndServicesAdd } from '@/api/goods.js'
import { reactive, ref } from 'vue'
import { ElMessage } from 'element-plus'
const props = defineProps({
    isAdd: {
        type: Boolean,
        default: false, // 默认值为 true
    },
    row: {
        type: Object,
        default: () => ({}), // 默认值为一个空对象
    },
})
const emit = defineEmits(['closeAdd', 'closeOK'])
const formSize = ref('default')
const ruleFormRef = ref()
const ruleForm = reactive({
    name: '',
    description: '',

})

const rules = reactive({
    name: [
        { required: true, message: '请输入', trigger: 'blur' },
        
    ],
    description: [
        { required: true, message: '请输入', trigger: 'blur' },
        
    ],
})

const submitForm = async (formEl) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
            if (props.isAdd) {
                goodsAndServicesAdd(ruleForm).then(res => {
                    if (res.code == 200) {
                        ElMessage({
                            type: 'success',
                            message: '添加成功',
                        })
                        emit('closeOK')
                    }
                })
            } else {
                goodsAndServicesUpdate({ ...ruleForm, id: props.row.id }).then(res => {
                    if (res.code == 200) {
                        ElMessage({
                            type: 'success',
                            message: '修改成功',
                        })
                        emit('closeOK')
                    }
                })
            }
        } else {
            console.log('error submit!', fields)
        }
    })
}

const resetForm = () => {
    emit('closeAdd')
}


onMounted(() => {
    if (!props.isAdd) {
        ruleForm.name = props.row.name;
        ruleForm.description = props.row.descript;
    }
})

</script>

<style lang="scss" scoped></style>